package mobile.persistencia;

import mobile.dominio.Cliente;
import mobile.dominio.Palm;
import mobile.dominio.Zona;
import waba.io.Catalog;
import waba.io.DataStream;
import waba.io.IOError;
import waba.io.ResizeRecord;
import waba.sys.Settings;

public class PPalm extends Catalog {
	private ResizeRecord rs;
	private DataStream ds;

	public static PPalm instance = new PPalm();

	/**
	 * Constructor which creates or open ( if it already exists ) the Customers.pdb file,
	 * attach the ResizeRecord and DataStream. The pragmatic way of reading/writing to a
	 * Catalog is by attaching those streams (ResizeRecord/DataStream) so that the resizing
	 * of the Catalog and information writing/reading are performed by those classes
	 */
	public PPalm()
	{
		super("Palm.mGqv.DATA", Catalog.CREATE);
		//super("Palm."+ Settings.appCreatorId +".DATA", Catalog.CREATE);
		rs = new ResizeRecord(this, 128);
		ds = new DataStream(rs);
	}
	
	public void write(Palm unaPalm, boolean update)
	{
		try {
			if (update){
				int n = indexOf(unaPalm);
				if (n == -1 || !rs.restartRecord(n)) 
					return;
			}else{
				rs.startRecord(); /* start the record at the next available position */
			}

			unaPalm.saveTo(ds);
			rs.endRecord(); /* finishes the writing of a record */
		} catch (IOError e) {}
	}

	/**
	 * Find the index ( position ) of the record ( Customer ) inside the pdb file
	 * 
	 * @param cli
	 *           the Customer
	 * @return the index position or -1 if the Customer was not found on the record
	 */
	public int indexOf(Palm unPalm){
		for (int n = this.getRecordCount() - 1; n >= 0; n--)
			try {
				if (this.setRecordPos(n)) {
					Palm elPalm = read();

					if (elPalm.getId() == unPalm.getId()) {
						return n;
					}
				}
			} catch (IOError e) {

			}
			return -1;
	}
	
	/**
	 * Reads a record ( Customer ) and construct a Customer. Notice that the order in which
	 * you read informations from the Customer is relevant.
	 * 
	 * @return the Customer
	 */
	public Palm read()
	{
		return new Palm(ds);
	}
	
	/**
	 * Returns a specific record ( Customer )
	 * 
	 * @param name
	 *           Name of the Customer
	 * @return The Customer or null if the Customer was not found
	 */
	public Palm obtenerPalmXID(int id) // info
	{
		for (int n = this.getRecordCount() - 1; n >= 0; n--)
			try {
				if (this.setRecordPos(n)){
					Palm unPalm = read();
					if (id == unPalm.getId()){
						return unPalm;
					}
				}
			} catch(IOError e){
			}
			return null;
	}
}
